//
//  ZLDetailPoemViewController.m
//  LittleFairyPoet
//
//  Created by rimi on 15/9/8.
//  Copyright (c) 2015年 周林. All rights reserved.
//

#import "ZLDetailPoemViewController.h"
#import "ZLZhushiViewController.h"

#define POEM_PATH [[NSBundle mainBundle]pathForAuxiliaryExecutable:@"poem.plist"]
#define COLLECTED_POEM_PATH NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject

static NSInteger const bgImageCount = 5;

@interface ZLDetailPoemViewController ()
{
    NSArray *_dataSource;
    NSMutableArray *_collectedPoemArray;
    NSString *_path;
}
@property (nonatomic, strong) UILabel *content /**< 诗正文 */;
@property (nonatomic, strong) UIButton *zhushiButton /**< 注释按钮 */;
@property (nonatomic, strong) UIButton *ceshiButton /**< 测试按钮 */;
@property (nonatomic, strong) UIButton *langduButton /**< 朗读按钮 */;
@property (nonatomic, strong) UIButton *nextButton /**< 下一首按钮 */;
@property (nonatomic, strong) UIScrollView *mainScrollView /**< 主滚动视图 */;
@property (nonatomic, strong) UILabel *titleLabel /**< 标题 */;
@property (nonatomic, strong) UILabel *author /**< 作者 */;
- (void)initializeDataSource; /**< 初始化数据源 */
- (void)initializeUserInterface; /**< 初始化用户界面 */
@end

@implementation ZLDetailPoemViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    CALayer *layer = [CALayer layer];
    layer.bounds = self.view.bounds;
    layer.position = self.view.center;
    NSInteger bgImageNo = arc4random() % (bgImageCount - 1) + 1;
    NSString *bgImageName = [NSString stringWithFormat:@"背景%ld.jpg",bgImageNo];
    layer.contents = (__bridge id)(IMAGE_CONTENT(bgImageName)).CGImage;
    [self.view.layer addSublayer:layer];
    [self.baseNavigationBar removeFromSuperview];
    [self.view addSubview:self.baseNavigationBar];
    self.baseNavigationBar.backgroundColor = [UIColor clearColor];
    [self initializeDataSource];
    [self initializeUserInterface];
//    [UILabel appearance].font = [UIFont fontWithName:@"KaiTi" size:20];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

#pragma mark - private
- (void)initializeDataSource {
    
    _dataSource = self.poemArray;
    NSFileManager *manager = [NSFileManager defaultManager];
    _path = [COLLECTED_POEM_PATH stringByAppendingString:@"/CollectedPoem.plist"];
    if ([manager fileExistsAtPath:_path]) {
        _collectedPoemArray = [NSMutableArray arrayWithContentsOfFile:_path];
    } else {
        _collectedPoemArray = [NSMutableArray array];
    }
}

- (void)initializeUserInterface {
    self.view.backgroundColor = [UIColor whiteColor];
    [self.rightButton setImage:IMAGE_CONTENT(@"收藏导航心.png") forState:UIControlStateNormal];
    [self.rightButton setImage:IMAGE_CONTENT(@"心-实底.png") forState:UIControlStateSelected];
    [self.mainScrollView addSubview:self.content];
    [self.view addSubview:self.zhushiButton];
    [self.view addSubview:self.ceshiButton];
    [self.view addSubview:self.nextButton];
    [self.view addSubview:self.mainScrollView];
    [self.view addSubview:self.titleLable];
    [self.view addSubview:self.author];
    self.mainScrollView.contentSize = CGSizeMake(0, CGRectGetMaxY(_content.frame));
    if ([_collectedPoemArray containsObject:_poemDic]) {
        self.rightButton.selected = YES;
    }
    self.titleLable.font = [UIFont fontWithName:@"KaiTi" size:20];
}

- (void)changeText {
    
//    self.titleLable.text = self.poemDic[@"title"];
    _content.frame = DHFlexibleFrame(CGRectMake(20, 0, ORIGIN_WIDTH, 64), NO);
    NSString *text = [self deleteHuanhangfuWithString:_poemDic[@"content"]];
    [text copy];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:text];
    paragraphStyle.lineSpacing = 10;
    paragraphStyle.alignment = NSTextAlignmentLeft;
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, text.length)];
    
    _content.attributedText = attributedString;
    [_content sizeToFit];
    CGPoint center = CGPointMake(ORIGIN_WIDTH / 2, _content.bounds.size.height / 2);
    if (center.y < self.view.center.y / 2) {
        center.y = self.view.center.y / 2;
    }
    _content.center = center;
    self.mainScrollView.contentSize = CGSizeMake(0, CGRectGetMaxY(_content.frame));
}

#pragma mark - responds events
- (void)respondsToTabBarRightButton:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        [_collectedPoemArray addObject:_poemDic];
        
        if ([_collectedPoemArray writeToFile: _path atomically:YES]) {
            
          [self initializeAlertControllerWithMessage:@"收藏成功"];
        } else {
            sender.selected = NO;
        }
    } else {
        
        [_collectedPoemArray removeObject:_poemDic];
        if ([_collectedPoemArray writeToFile:_path atomically:YES]) {
            
           [self initializeAlertControllerWithMessage:@"取消收藏成功"];
        } else {
            sender.selected = YES;
        }
        
    }
}

- (void)respondsToCeshi :(UIButton *)sender {
    
}

- (void)respondsToNextPoem :(UIButton *)sender {
    _poemSerialNo ++;
    if (_poemSerialNo >= _dataSource.count) {
        [self initializeAlertControllerWithMessage:@"已经是最后一首了"];
        _poemSerialNo --;
        return;
    }
    self.poemDic = _dataSource[_poemSerialNo];
    [self changeText];
}

- (void)respondsToZhushi :(UIButton *)sender {
    ZLZhushiViewController *zhushiVC = [ZLZhushiViewController new];
    zhushiVC.poem = self.poemDic;
    [self.navigationController pushViewController:zhushiVC animated:YES];
}

#pragma mark - private method
- (CGFloat) culculateHeightWithText :(NSString *) text font:(UIFont *)font {
    CGRect rect = [text boundingRectWithSize:DHFlexibleSize(CGSizeMake(ORIGIN_WIDTH - 20, MAXFLOAT), NO) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName : font} context:nil];
    return rect.size.height;
}

- (NSString *) deleteHuanhangfuWithString:(NSString *) string {
    NSMutableString *rtnString = [string mutableCopy];

    [rtnString replaceOccurrencesOfString:@"<p>" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, rtnString.length)];
    [rtnString replaceOccurrencesOfString:@"</p>" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, rtnString.length)];
    
    return rtnString;
}

#pragma mark - getter
- (UILabel *)content {
    if (!_content) {
        _content = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, ORIGIN_WIDTH, 64) adjustWidth:NO];
//        _content.font = [UIFont systemFontOfSize:14];
        _content.numberOfLines = 0;
        _content.textAlignment = NSTextAlignmentCenter;
        _content.font = [UIFont fontWithName:@"KaiTi" size:20];
        [self changeText];
    }
    return _content;
}

- (UIButton *)zhushiButton {
    if (!_zhushiButton) {
        _zhushiButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [_zhushiButton setTitle:@"注释" forState:UIControlStateNormal];
        _zhushiButton.bounds = DHFlexibleFrame(CGRectMake(0, 0, 100, 40), NO);
        _zhushiButton.center = CGPointMake(50 * DHFlexibleHorizontalMutiplier(), 420 * DHFlexibleVerticalMutiplier());
        [_zhushiButton addTarget:self action:@selector(respondsToZhushi:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _zhushiButton;
}

- (UIButton *)ceshiButton {
    if (!_ceshiButton) {
        _ceshiButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [_ceshiButton setTitle:@"我会背了" forState:UIControlStateNormal];
        _ceshiButton.bounds = DHFlexibleFrame(CGRectMake(0, 0, 100, 50), NO);
        _ceshiButton.center = CGPointMake(265 * DHFlexibleHorizontalMutiplier(), 420 * DHFlexibleVerticalMutiplier());
    }
    return _ceshiButton;
}

- (UIButton *)nextButton {
    if (!_nextButton ) {
        _nextButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [_nextButton setTitle:@"下一首" forState:UIControlStateNormal];
        _nextButton.bounds = DHFlexibleFrame(CGRectMake(0, 0, 100, 50), NO);
        _nextButton.center = CGPointMake(ORIGIN_WIDTH * DHFlexibleHorizontalMutiplier() / 2, CGRectGetMaxY(self.ceshiButton.frame) + 50);
        [_nextButton addTarget:self action:@selector(respondsToNextPoem:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _nextButton;
}

- (UIScrollView *)mainScrollView {
    if (!_mainScrollView) {
        _mainScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 135, ORIGIN_WIDTH, ORIGIN_HEIGHT - 250) adjustWidth:NO];
    }
    return _mainScrollView;
}

- (UILabel *)titleLable {
    if (!_titleLabel) {
        
        _titleLabel = ({
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(60, 60, 180, 40) adjustWidth:NO];
            //label.backgroundColor = [UIColor orangeColor];
            label.textAlignment = NSTextAlignmentCenter;
            label.numberOfLines = 0;
            label.text = _poemDic[@"title"];
//            label.textColor = ZLColor(119, 66, 32);
            label.font = [UIFont fontWithName:@"KaiTi" size:22];
            label.font = [UIFont fontWithName:@"AmericanTypewriter-Bold" size:22];
            label;
        });
    }
    return _titleLabel;
}

- (UILabel *)author {
    if (!_author) {
        
        _author = ({
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(120, 100, 180, 40) adjustWidth:NO];
            //label.backgroundColor = [UIColor orangeColor];
            label.textAlignment = NSTextAlignmentRight;
            label.numberOfLines = 0;
            label.text = [NSString stringWithFormat:@"%@·%@",_poemDic[@"chaodai"], _poemDic[@"zuozhe"]];
//            label.textColor = ZLColor(119, 66, 32);
            label.font = [UIFont fontWithName:@"KaiTi" size:16];
            label;
        });
    }
    return _author;
}

@end
